package com.icss.trans.send.httpput;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icss.trans.cfg.BaseProperties;
import com.icss.trans.exception.TransException;

/**
 * 
 * @ClassName: HttpConnector
 * @Description:
 * @author ICSS
 * @date 2015-3-25 下午2:41:58
 * 
 */
public class HttpSender {

    protected static Logger logger = LoggerFactory.getLogger(HttpSender.class);

    public HttpSender() {
    }

    /**
     * 
     * @Description: 调用传输前置发送文件
     * @param param
     * @return 返回200为成功  其他为失败
     * @throws Exception
     */
    public static int sendData(SendParam param) throws TransException {
        long startTime = System.currentTimeMillis();
        int resultCode = 400;
        HttpClient httpclient = null;
        HttpPost post = null;

        try {
            httpclient = new DefaultHttpClient();
            httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
            String sendUrl = BaseProperties.getInstance().getTransUrl();
            post = new HttpPost(sendUrl + "/transEntrance");
            HttpResponse response = null;

            post.setEntity(param.buildMultipartEntity());
            logger.debug("sendData:param:" + param.toString());

            response = httpclient.execute(post);
            resultCode = response.getStatusLine().getStatusCode();
            String resultStr = EntityUtils.toString(response.getEntity());
            logger.debug("EI sendData result:" + resultStr);

            if (!"fail".equals(resultStr) && resultCode == HttpStatus.SC_OK) {
                resultCode = HttpStatus.SC_OK;
            } else {
                logger.error("send file is error!!!resultStr:" + resultStr);
                logger.error("send file is error!!!sendData:param:" + param.toString());
            }
            logger.debug("sendData ok!used time:" + (System.currentTimeMillis() - startTime));
        } catch (Exception e) {
            logger.error("send data to ei error!" + e.getMessage() + "[" + param.toString() + "][" + post.getURI()
                    + "]", e);
            throw new TransException("http sendData error：" + e.getMessage(), e);
        } finally {
            post.releaseConnection();
            httpclient.getConnectionManager().shutdown();
            post = null;
            httpclient = null;
        }
        return resultCode;
    }

}
